﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Web.Api.Server.Models;

namespace Web.Api.Server.Services.IdentityServer4
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly ApplicationDbContext _dbContext;

        public ResourceOwnerPasswordValidator(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user = _dbContext.Users
                .Where(u => u.Name == context.UserName)
                .ToOne();

            //验证失败
            if (user != null && BCrypt.Net.BCrypt.Verify(context.Password, user.Password))
            {
                //subjectId 为用户唯一标识 一般为用户id
                //authenticationMethod 描述自定义授权类型的认证方法 
                //authTime 授权时间
                //claims 需要返回的用户身份信息单元
                context.Result = new GrantValidationResult(
                    user.Id.ToString(),
                    OidcConstants.AuthenticationMethods.Password,
                    DateTime.UtcNow,
                    new List<Claim>()
                    {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Role, "admin")
                    });

                return Task.CompletedTask;
            }

            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户不存在或密码错误");
            return Task.CompletedTask;
        }
    }
}
